package sz.szsmk.citizencard.ui.dzsmkavtivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.dialog.OneButtonProDialog;
import sz.szsmk.citizencard.entity.UploadHeadImgEntry;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.QuerLeisureCardsInfoRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.mvp.ApplicationAuthorMvpView;
import sz.szsmk.citizencard.mvp.BasePresenter;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.ApplicationAuthorPresenter;
import sz.szsmk.citizencard.ui.activity.SelectImageActivity;
import sz.szsmk.citizencard.ui.dialogs.LeisureYearCardsDialog;
import sz.szsmk.citizencard.ui.dialogs.UpLoadHeadImgDialog;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Base64;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PhotoUtils;

import static java.lang.String.valueOf;

/**
 * 应用授权
 */
@Route("applicationAuthorActivity")
public class ApplicationAuthorActivity extends AppBaseActivity
        implements ApplicationAuthorMvpView,UpLoadHeadImgDialog.UPLoadHeadImgCallBack {

    @Inject
    ApplicationAuthorPresenter presenter;
    TextView submit;
    TextView tvTitle;
    ImageView authIcon;
    TextView authDes;
    TextView idname;
    TextView appName;
    private String title;
    private String userName;
    private String aCard;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent().inject(this);
        setContentView(R.layout.qr_activity_application_author);

        submit = findViewById(R.id.submit);
        tvTitle= findViewById(R.id.tv_title);
        authIcon= findViewById(R.id.auth_icon);
        authDes= findViewById(R.id.auth_des);
        idname= findViewById(R.id.idname);
        appName= findViewById(R.id.app_name);

        submit.setOnClickListener(this::onViewClicked);

        title = getIntent().getStringExtra(Constant.TYPE);
        userName = getIntent().getStringExtra(Constant.ID_NAME);
        idname.setText(userName + "：您好");
        submit.setEnabled(true);
        if (title.equals("ghf")) {
            tvTitle.setText("应用授权(桂花分)");
            appName.setText("桂花分");
            authIcon.setImageResource(R.drawable.apphome_ghf);
            authDes.setText("将您的桂花分信息同步至电子市民卡");
        }
        if (title.equals("xxnk")) {
            tvTitle.setText("应用授权(休闲年卡)");
            appName.setText("惠民休闲年卡");
            authIcon.setImageResource(R.drawable.home_grid_xxnk);
            authDes.setText("是否同意将您实名办理的休闲年卡套餐加载到您的身份码？您授权同意后可凭身份码直接刷码进入套餐内任意景点，身份码与实体卡数据贯通。");
        }
        if (title.equals("gjj")) {
            tvTitle.setText("应用授权(公积金)");
            appName.setText("公积金");
            authIcon.setImageResource(R.drawable.apphome_gjj);
            authDes.setText("将您的公积金信息同步至电子市民卡");
        }
        if (title.equals("whxf")) {
            tvTitle.setText("应用授权(文化消费)");
            appName.setText("文化消费");
            aCard = getIntent().getStringExtra(Constant.A_CARD);
            authIcon.setImageResource(R.drawable.auth_icon_whxf);
            authDes.setText("是否同意将实名身份信息加载到身份码？\n授权同意后，在文化消费合作商家线下消费时，扫码可享协议价格优惠");
        }

        if (title.equals("sb")) {
            tvTitle.setText("应用授权(社保)");
            appName.setText("社保");
//            aCard = getIntent().getStringExtra(Constant.A_CARD);
            authIcon.setImageResource(R.drawable.icon_sb);
            authDes.setText("将您的社保信息同步至电子市民卡。");
        }
        if (title.equals("tyhm")) {
            tvTitle.setText("应用授权(体育惠民)");

            aCard = getIntent().getStringExtra(Constant.A_CARD);
            appName.setText("体育惠民");
            authIcon.setImageResource(R.drawable.auth_icon_tyhm);
            authDes.setText("是否同意将实名身份信息加载到身份码？\n授权同意后，在体育惠民线下合作场馆消费时，扫码享协议价");
        }

        idname.setVisibility(View.GONE);
    }

    @Override
    protected CharSequence getTopTitle() {
        return "";
    }

    @Override
    protected BasePresenter[] initPresenters() {
        return new BasePresenter[]{presenter};
    }

    @Override
    public void success() {

    }

    @Override
    public void fail() {

    }

    @Override
    public void authSucc(BaseBean response) {
        OneButtonProDialog passwordDialog = new OneButtonProDialog();
        passwordDialog.setAction(1);
        passwordDialog.setContent(response.getMessage());
        passwordDialog.setTitle("苏州市民卡");
        passwordDialog.setCancelText("我知道了");
        passwordDialog.setOkText("我是确定");
        passwordDialog.setOnCancelClickListener(new OneButtonProDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                jumpController();
                //   finish();
//                Toast.makeText(BankAdminActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
        passwordDialog.setOnOkClickListener(new OneButtonProDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {

//                Toast.makeText(BankAdminActivity.this, "开启", Toast.LENGTH_SHORT).show();
            }
        });
        passwordDialog.show(getFragmentManager(), null);

    }

    private void jumpController() {
        if (title.equals("ghf")) {
            presenter.selectUserAuth("ghf");
        }
        if (title.equals("xxnk")) {
            finish();
        }
        if (title.equals("gjj")) {
            presenter.selectUserAuth("gjj");
        }
        if (title.equals("whxf")) {
            finish();
        }

        if (title.equals("sb")) {
            presenter.selectUserAuth("sb");
        }
        if (title.equals("tyhm")) {
            finish();
        }
    }

    @Override
    public void authFail(BaseBean response) {

    }


    QuerLeisureCardsInfoRes.QuerLeisureCardsInfoBean lcTempForUpload;

    LeisureYearCardsDialog leisureYearCardsDialog;

    @Override
    public void queryLeisureSucc(QuerLeisureCardsInfoRes response) {

        List<QuerLeisureCardsInfoRes.QuerLeisureCardsInfoBean> leisur_cards = response.getLeisur_cards();

//        leisur_cards.get(0).setIsHavingPicture(0);

        if (leisur_cards != null) {
            if (leisur_cards.size() == 0) {
                Toast.makeText(this,"暂无相关休闲年卡",Toast.LENGTH_LONG).show();
            } else {
            leisureYearCardsDialog = new LeisureYearCardsDialog(this,
                    new LeisureYearCardsDialog.ILeisureYearCardsDialog() {
                        @Override
                        public void lyCardsCallBack(QuerLeisureCardsInfoRes.QuerLeisureCardsInfoBean lcTemp, int type) {


                            //再打开一个 dialog

                            if(type==1){
                                //上传头像

                                lcTempForUpload = lcTemp;

                                UpLoadHeadImgDialog upLoadHeadImgDialog = new UpLoadHeadImgDialog(ApplicationAuthorActivity.this);
                                upLoadHeadImgDialog.setUpLoadHeadImgCallBack(ApplicationAuthorActivity.this);
                                upLoadHeadImgDialog.show();


                            }else{
                                leisureYearCardsDialog.dismiss();
                                //绑定
                                presenter.cardnoAuthorization("1", lcTemp.getCardNo());
                            }


                        }
                    },leisur_cards);

            leisureYearCardsDialog.show();

            }
        }else{
            Toast.makeText(this,"暂无相关休闲年卡",Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void queryLeisureFail(QuerLeisureCardsInfoRes response) {

    }

    @Override
    public void cardnoAuthorizationSucc(BaseBean response) {
        OneButtonProDialog passwordDialog = new OneButtonProDialog();
        passwordDialog.setAction(1);
        passwordDialog.setContent(response.getMessage());
        passwordDialog.setTitle("苏州市民卡");
        passwordDialog.setCancelText("我知道了");
        passwordDialog.setOkText("我是确定");
        passwordDialog.setOnCancelClickListener(new OneButtonProDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                finish();
            }
        });
        passwordDialog.setOnOkClickListener(new OneButtonProDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {
            }
        });
        passwordDialog.show(getFragmentManager(), null);

    }

    @Override
    public void cardnoAuthorizationFail(BaseBean response) {
        OneButtonProDialog passwordDialog = new OneButtonProDialog();
        passwordDialog.setAction(1);
        passwordDialog.setContent(response.getMessage());
        passwordDialog.setTitle("苏州市民卡");
        passwordDialog.setCancelText("我知道了");
        passwordDialog.setOkText("我是确定");
        passwordDialog.setOnCancelClickListener(new OneButtonProDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                finish();
//                Toast.makeText(BankAdminActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
        passwordDialog.setOnOkClickListener(new OneButtonProDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {

//                Toast.makeText(BankAdminActivity.this, "开启", Toast.LENGTH_SHORT).show();
            }
        });
        passwordDialog.show(getFragmentManager(), null);

    }

    @Override
    public void selectUserAuthFail() {

    }

    @Override
    public void selectUserAuthSucc(SeleciUserAuthRes response, String type) {
        String access_token = ACache.get(mContext).getAsString("access_token");
        List<SeleciUserAuthRes.AuthTypeListBean> authTypeList = response.getAuthTypeList();

        if (type.equals("gjj")) {
            String isAuth = authTypeList.get(1).getIsAuth();
            //0未授权，1已授权，2未实名(L3认证)
            if (isAuth.equals("2")) {
                JumpUtils.jump(mContext, "RealNameActivity", 0);
                finish();
            } else if (isAuth.equals("1")) {
                //跳转公积金
                Bundle bundle = new Bundle();
                String path = Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + access_token;
                bundle.putString("url", path);

                JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
                finish();
            } else if (isAuth.equals("0")) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.TYPE, "gjj");
                JumpUtils.jumptoNatvie(mContext, "applicationAuthorActivity", 0, bundle);
                finish();
            }

        }

        if (type.equals("sb")) {
            String isAuth = authTypeList.get(0).getIsAuth();
            //0未授权，1已授权，2未实名(L3认证)
            if (isAuth.equals("2")) {
                JumpUtils.jump(mContext, "RealNameActivity", 0);
                finish();
            } else if (isAuth.equals("1")) {
                //跳转社保
                Bundle bundle = new Bundle();
                String path = Constant.BASE_URL + "app-front-end/#/social/main?access_token=" + access_token;
                bundle.putString("url", path);
                JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
                finish();
            } else if (isAuth.equals("0")) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.TYPE, "sb");
                JumpUtils.jumptoNatvie(mContext, "applicationAuthorActivity", 0, bundle);
                finish();
            }

        }

        if (type.equals("ghf")) {
            String isAuth = authTypeList.get(2).getIsAuth();
            //0未授权，1已授权，2未实名(L3认证)
            if (isAuth.equals("2")) {
                JumpUtils.jump(mContext, "RealNameActivity", 0);
                finish();
            } else if (isAuth.equals("1")) {
//                Bundle bundle = new Bundle();
//                String path = Constant.BASE_URL + "app-front-end/#/social/main?access_token=" + access_token;
//                bundle.putString("url", path);
//                JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
                presenter.getGetOrderId("", "ghf");

            } else if (isAuth.equals("0")) {
                Bundle bundle = new Bundle();
//                bundle.putString(Constant.TYPE, "ghf");
                bundle.putString(Constant.TYPE, "ghf");
                JumpUtils.jumptoNatvie(mContext, "applicationAuthorActivity", 0, bundle);
                finish();
            }
        }
    }

    @Override
    public void getGetOrderIdSucc(GetOrderOpenidRes response, String s, String type) {
        if (type.equals("ghf")) {
            //跳转桂花分
            String url = Constant.SZ_URL +"?"+ response.getExtend();
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString(Constant.TITLE, "桂花分");
            JumpUtils.jumptoNatvie(mContext, "webView", 0, bundle);
            finish();
        }
    }

    @Override
    public void getGetOrderIdFail() {

    }

    @Override
    public void getUploadPic() {
        Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
        leisureYearCardsDialog.dismiss();

//        presenter.quryLeisureCards();

        //头像上传后 直接绑定 绑定
        presenter.cardnoAuthorization("1", lcTempForUpload.getCardNo());
    }


    public void onViewClicked(View view) {
        if (view.getId() == R.id.submit) {
            if (title.equals("ghf")) {
                presenter.applicationAuthor("3");
            }
            if (title.equals("gjj")) {
                presenter.applicationAuthor("2");
            }

            if (title.equals("sb")) {
                presenter.applicationAuthor("1");
            }

            if (title.equals("xxnk")) {
                presenter.quryLeisureCards();
            }

            if (title.equals("whxf")) {
                presenter.cardnoAuthorization("3", aCard);
            }

            if (title.equals("tyhm")) {
                presenter.cardnoAuthorization("2", aCard);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==100 && resultCode==100 && data!=null){

            UploadHeadImgEntry eventBusBean = new UploadHeadImgEntry();
            eventBusBean.setPath(data.getStringExtra("imagePath"));
            EventBus.getDefault().post(eventBusBean);
        }
    }


    //以下为上传头像
    private void upLoad(String path) {

        File files = compressImage(PhotoUtils.getBitmapFromUri(Uri.fromFile(new File(path)), this));
        Map<String, Object> params = new HashMap<>();
        params.put("cardNo", lcTempForUpload.getCardNo());

            BitmapFactory.Options options =new BitmapFactory.Options();

            options.inJustDecodeBounds=false;
            Bitmap bitmaptemp = BitmapFactory.decodeFile(files.getAbsoluteFile().toString());

            String photo = Bitmap2StrByBase64(bitmaptemp);

            presenter.upLoadPic( lcTempForUpload.getCardNo(),photo);

    }


    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + "app_icon.png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
//                BAFLogger.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
//            BAFLogger.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }


    public String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
//        return Base64.encodeToString(bytes, Base64.DEFAULT);



        return Base64.encode(bytes);


//        return new String(Base64.encode(bytes, Base64.DEFAULT),"utf-8");
    }



    //这个是选择头像的回调
    @Override
    public void callback(ImageView imageView) {
        startActivityForResult(new Intent(this, SelectImageActivity.class),100);
    }

    @Override
    public void upLoadImg(String path) {
        upLoad(path);
    }

}
